<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>websocket</title>
    <link href="//cdn.bootcss.com/normalize/4.2.0/normalize.min.css" rel="stylesheet">
</head>

<body>
    <div style="width: 550px;margin:0 auto;">
        <div id="result" style="max-height: 800px;overflow-y: scroll;">
        </div>
        <input type="text" id="word" disabled="true">
        <button id="send" disabled="true">send</button>
    </div>
    <script type="text/javascript">
    var result = document.getElementById('result'),
        word = document.getElementById('word'),
        send = document.getElementById('send'),
        showInfo = function(info) {
            var p = document.createElement('p')
            p.innerHTML = info
            result.appendChild(p)
            p = null
        },
        sendInfo = function(e) {
            ws.send(word.value)
        }

    var ws = new WebSocket('ws://localhost:8081/')
    ws.onopen = function() {
        showInfo('ws open')
        word.disabled = false
        send.disabled = false
        send.addEventListener('click', sendInfo)
    }
    ws.onmessage = function(e) {
        showInfo(e.data + ' --from server')
    }
    ws.onclose = function() {
        showInfo('ws close')
        word.disabled = true
        send.disabled = true
        send.removeEventListener('click', sendInfo)
    }
    ws.onerror = function() {
        showInfo('ws error')
        word.disabled = true
        send.disabled = true
        send.removeEventListener('click', sendInfo)
    }
    </script>
</body>

</html>
